const postfix = 'IkNxixzqo5DPdd3A'; // 缓存前缀
const TokenKey = 'vue_uni_app_token'
const OpenIDKey = 'vue_uni_app_openid'


/**
 * 设置缓存
 * @param  {[type]} key  [description]
 * @param  {[type]} data [description]
 * @param  {[type]} time [description]
 * @return {[type]}      [description]
 */
export function setOpenID(data, time = 7200) {
	let key = OpenIDKey;
	uni.setStorageSync(key, data);
	var seconds = parseInt(time);
	if (seconds > 0) {
		var timestamp = Date.parse(new Date());
		timestamp = timestamp / 1000 + seconds;
		uni.setStorageSync(key + postfix, timestamp + '');
	} else {
		uni.removeStorageSync(key + postfix);
	}
}

/**
 * 获取缓存
 * @param  {[type]} key [description]
 * @param  {[type]} def [description]
 * @return {[type]}     [description]
 */
export function getOpenID(def) {
	let key = OpenIDKey;
	var deadtime = parseInt(uni.getStorageSync(key + postfix));
	if (deadtime) {
		if (parseInt(deadtime) < Date.parse(new Date()) / 1000) {
			if (def) {
				return def;
			} else {
				uni.removeStorageSync(key + postfix);
				return false;
			}
		}
	}
	var res = uni.getStorageSync(key);
	if (res) {
		return res;
	} else {
		if (def == undefined || def == '') {
			def = false;
			uni.removeStorageSync(key);
		}
		return def;
	}
}

/**
 * 移除缓存
 * @param  {[type]} key [description]
 * @return {[type]}     [description]
 */
export function removeOpenID() {
	let key = OpenIDKey;
	uni.removeStorageSync(key);
	uni.removeStorageSync(key + postfix);
}

/**
 * 设置缓存
 * @param  {[type]} key  [description]
 * @param  {[type]} data [description]
 * @param  {[type]} time [description]
 * @return {[type]}      [description]
 */
export function setToken(data, time = 7200) {
	let key = TokenKey;
	uni.setStorageSync(key, data);
	var seconds = parseInt(time);
	if (seconds > 0) {
		var timestamp = Date.parse(new Date());
		timestamp = timestamp / 1000 + seconds;
		uni.setStorageSync(key + postfix, timestamp + '');
	} else {
		uni.removeStorageSync(key + postfix);
	}
}

/**
 * 获取缓存
 * @param  {[type]} key [description]
 * @param  {[type]} def [description]
 * @return {[type]}     [description]
 */
export function getToken(def) {
	let key = TokenKey;
	var deadtime = parseInt(uni.getStorageSync(key + postfix));
	if (deadtime) {
		if (parseInt(deadtime) < Date.parse(new Date()) / 1000) {
			if (def) {
				return def;
			} else {
				uni.removeStorageSync(key + postfix);
				return false;
			}
		}
	}
	var res = uni.getStorageSync(key);
	if (res) {
		return res;
	} else {
		if (def == undefined || def == '') {
			def = false;
			uni.removeStorageSync(key);
		}
		return def;
	}
}

/**
 * 移除缓存
 * @param  {[type]} key [description]
 * @return {[type]}     [description]
 */
export function removeToken() {
	let key = TokenKey;
	uni.removeStorageSync(key);
	uni.removeStorageSync(key + postfix);
}

/**
 * 清理缓存
 * @return {[type]} [description]
 */
export function clearToken() {
	uni.clearStorageSync();
}
